var itemno = "";
var applyid = "";
var nodeno = "";
var orgcode = "";
var nodename = "";
var nextnodecode1 = "";
var selectID = "userlist";

var instanceid;
var pinstanceid;
var flowtaskid;
var applyid;
var taskuserid;

$(function(){
	var applyno = getUrlParam("applyno");
	instanceid = getUrlParam("instanceid");
	pinstanceid = getUrlParam("pinstanceid");
	flowtaskid = getUrlParam("flowtaskid");
	applyid= getUrlParam("applyid");
	taskuserid=getUrlParam("taskuserid");
	bindApplyForm(applyno);
	$('#jointlysignopinion').hide();
	$('#materialList').hide();
	$('#cerinfo').hide();
	
	initFileInput('upload', null, null);
//	上传文本控件关闭事件 -- 清除内容
	$('#fileuploadmodal').on('hide.bs.modal', function () {
        setTimeout(function(){
        	$('.fileinput-remove').trigger('click');
        }, 1000);
	})
})
function openModal(){
	$('#fileuploadmodal').modal('show');
}
function initFileInput(ctrlcss, params, data) {
	
	var urls = [];
	if(data != null){
		for(var i = 0; i < data.length; i++){
			urls[i] = data[i].url;
		}
	}
    var control = $('.' + ctrlcss);
    control.fileinput({
        theme: 'explorer-fa',
        language: 'zh', //设置语言
        uploadUrl: projectPath + "upload_auditannex.do", //上传的地址
		allowedFileExtensions : ['jpg', 'png','gif','txt','sql','xlsx','xls','pdf','pptx','docx','doc','jpeg'],//接收的文件后缀
        uploadAsync: true, //默认异步上传
        showUpload: true, //是否显示上传按钮
        showRemove : true, //显示移除按钮
        showPreview : true, //是否显示预览
        showCaption: false,//是否显示标题
        browseClass: "btn btn-primary", //按钮样式
        enctype: 'multipart/form-data',
        validateInitialCount:true,
        overwriteInitial: false,
        initialPreviewAsData: true,
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        initialPreview: urls,
	    initialPreviewConfig: data,

    }).on('filepreupload', function(event, data, previewId, index) {     //上传中
        var form = data.form, files = data.files, extra = data.extra,
        response = data.response, reader = data.reader;
        console.log(JSON.stringify(data.form));
        console.log('文件正在上传');
    }).on("fileuploaded", function (event, data, previewId, index) {    //一个文件上传成功
        var resultData = data.response;
        if(data.response.result=="1"){
        	var html='<a target="_blank" id=annexid'+data.response.datas.annexid+' data={"annexid":"'+data.response.datas.annexid+'"} href="/gahCMP/business/getannexidbyid.do?annexid='+data.response.datas.annexid+'"><button type="button" class="btn btn-link">'+data.response.datas.filename+'</button></a>';
             $("#auditannex").append(html);  
        }
        
        $('#fileuploadmodal').modal('hide');
    }).on('fileerror', function(event, data, msg) {  //一个文件上传失败
        console.log('文件上传失败！'+data.id);
    }).on('filepredelete', function(event, key, jqXHR, data) {  
        alert(key);   
        return;
    });  
    

	
	//*****************常用意见相关代码段*****************
	//添加常用意见
	$('#commonopinion').click(function(){
		
		var opinion = $('#opinion').val();
		if('' == opinion){
	    	window.wxc.xcConfirm("意见不能为空！", window.wxc.xcConfirm.typeEnum.error, {
	    		onOk: function(){
	    			return;
	    		}
	    	});
		}
		else{
			var params = {
					opinion : opinion
			};
	
			$.ajax({ 
				url: basePath() + 'sys/addcommonopinion.do',
				data: JSON.stringify(params),
				dataType: "json",
				type : "post",
		        contentType: "application/json",
				success: function(data){
			    	window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.info, {
			    		onOk: function(){
			    		}
			    	});
		      	}
			});
		}
	});
	
	//查询当前登录用户的常用意见
	findCommonOpinion();
	
	//*****************常用意见相关代码段*****************
}

function bindOpinion(opinion){
	$('#opinion').val(opinion);
}
function findCommonOpinion(){
	$.ajax({ 
		url: basePath() + 'sys/findcommonopinion.do',
		dataType: "json",
		type : "get",
        contentType: "application/json",
		success: function(data){
			if(data.result == "1"){
				
				var datas = data.datas;
				for(var i = 0; i < datas.length; i++){
					var opinion = datas[i];
					var html = '<li><a href="#" onclick="bindOpinion(\''+ opinion.opinion +'\')">'+ opinion.opinion +'</a></li>';
					
					$('#commonopinionmenu').append(html);
				}
			}
      	}
	});
}

function bindApplyForm(applyno){

	$.ajax({ 
		url: basePath() + 'business/getapplyinfo.do',
		data: {"applyno": applyno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		itemno = data.datas.itemno;
	    		
	    		
	    		for(var d in data.datas){//遍历json对象的每个key/value对,p为key
	    			if(d == 'applytime'){
	    				$('#' + d).html(formatDate(data.datas[d], 'yyyy-mm-dd hh:mi'));
	    			}
	    			else{
	    				$('#' + d).html(data.datas[d] == '' ? '/' : data.datas[d]);
	    				
	    				if(d == 'nodename' && data.datas[d] == '制证'){
	    					$('#cerinfo').show();
	    				}
	    				else if(d == 'nodename' && data.datas[d].indexOf('初审') > 0){
	    					getNodeParamInfo(data.datas['nodeno']);
	    				}
	    			}
	    		}
	    		

	    		
	    		orgcode = data.datas.orgcode;
	    		
	    		applyid = data.datas.applyid;
	    		nodeno = data.datas.nodeno;
	    		$("#downallmaterial").attr("href","/gahCMP/business/downAllmaterial.do?applyid="+applyid);

	    		//绑定审批意见
	    		bindAuditOpinion(applyid,pinstanceid);
	    		
	    		//绑定业务资料
	    		bindBusinessForm(applyid);
	    		

	    		$('#ifBusiness').load('detail/'+ itemno +'.html');

//	    		//绑定船舶数据
//	    		bindShipForm(applyid);	 
	    		
	    		//绑定附件材料
	    		bindMaterialListForm(applyid);	    

	    		//查询文书
	    		getBookByApplyid(applyid);
	    		
	    		//绑定下一节点
	    		bindNextNode(flowtaskid);
	    		
	    		bindingJointlySignOpinion();

	    	}
      	}
	});
}


//function bindShipForm(applyid){
//	$.ajax({ 
//		url: basePath() + 'business/getshipinfo.do',
//		data: {"applyid": applyid},
//		dataType: "json",
//        contentType: "application/json",
//		success: function(data){
//	    	if(data.result == 1){
//	    		for(var i=0; i< data.datas.length; i++){
//	    			bindShipData(data.datas[i]);
//	    		}
//	    	}
//      	}
//	});
//}
function bindShipData(jsonShip){
	for(var d in jsonShip){
		$('#' + d).html(jsonShip[d]);
	} 
}

var businessData;
function bindBusinessForm(applyid){
	
	$.ajax({ 
		url: basePath() + 'business/getbusinessinfo.do',
		data: {"applyid": applyid, "itemno": itemno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		for(var d in data.datas){//遍历json对象的每个key/value对,p为key
	    			if(d == 'workbegintime' || d == 'workendtime' || d == 'executionbegintime' || d == 'executionendtime' || d == 'worktime' || d == 'workstarttime'){
	    				$('#' + d).html(formatDate(data.datas[d], 'yyyy-mm-dd'));
	    			}
	    			else{
	    				$('#' + d).html(data.datas[d] == '' ? '/' : data.datas[d]);
	    			}
	    		}
	    	}
      	}
	});
}

function bindMaterialListForm(applyid){
	$.ajax({ 
		url: basePath() + 'business/getmaterialinfo.do',
		data: {"applyid": applyid},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		bindMaterial(data.datas);
	    		
	    		for(var i=0; i<data.datas.length; i++)
	    			bindDetailList(data.datas[i]);
	    	}
      	}
	});
}

function getBookByApplyid(applyid){
	$.ajax({ 
		url: basePath() + 'business/getamanuensis.do',
		data: {"applyid": applyid},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		var bookData = data.datas;
	    		
	    		for(var i = 0; i < bookData.length; i++){
	    			var ahtml = '<a target="_blank" href="'+ bookData[i].fileurl +'"><button type="button" class="btn btn-link">'+ bookData[i].amanuensisname +'</button></a>'; 
	    			
	    			$('#book').append(ahtml);
	    		}
	    	}
      	}
	});
}

function bindNextNode(flowtaskid){
	$.ajax({ 
		url: basePath() + 'flow/getFlowTaskInfo.do',
		data: {"flowtaskid": flowtaskid},
		dataType: "json",
        contentType: "application/json",
        async:false,
		success: function(data){
			if(data.result == 1){
				var datas = data.datas;
				nodeno=datas.nodecode;
			}
      	}
	});
	
	$.ajax({ 
		url: basePath() + 'flow/getnextnodes.do',
		data: {"nodecode": nodeno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
			if(data.result == 1){
				var datas = data.datas;
				for(var i = 0; i < datas.length; i++){
					var nextnodecode = datas[i].nextnodecode;
					var nextnodename = datas[i].nextnodename;

					var controlhtml = '<input type="radio" value="'+ nextnodecode +'" text="'+ nextnodename +'"  name="nextnode" />';
					$("#nextnode").append(
							" <li>"
								+ controlhtml
								+ nextnodename
							+ "</li>");
				}
					    		

	    	    $("input[type=radio][name=nextnode]").bind("change", function() {

					$('#materialList').hide();
	    	    	
					// 先清空控件数据
					$('#' + selectID).empty(); 

					var nextnodecode = $(this).attr('value');
					nextnodecode1 = nextnodecode;

					$.ajax({ 
						url: basePath() + 'flow/getuserbynodecode.do',
						data: {"businessid": applyid, "nodecode": nextnodecode, "itemno": itemno, "orgcode": orgcode},
						dataType: "json",
				        contentType: "application/json",
						success: function(data){
					    	if(data.result == 1){

								for (var i = 0; i < data.datas.length; i++) {
									var value = data.datas[i].userid;
									var text = data.datas[i].username;
									
									var option = $("<option>").val(value).text(text).attr('data', JSON.stringify(data.datas[i])); 
									$('#' + selectID).append(option); 
								}
								
								var options = $('#' + selectID).find("option");
								options.first().attr("selected", true);
					    	}
				      	}
					});
					
					nodename = $(this).attr('text');
					if(nodename.indexOf('补正') >= 0){
						$('#materialList').show();
					}
				});
			}
      	}
	});
}

var tableID = 'material';
function bindMaterial(materialList){
	
    	
	for(var i = 0; i < materialList.length; i++){
		var ismustsubmit = materialList[i]['ismustsubmit'];
		var ismustsubmitStr = "";
		var must = false;
		if(ismustsubmit == 1){
			ismustsubmitStr = '<span style="color:red;">*</span>';
			must = true;
		}
		var index = materialList[i]['serialnumber'];
		var quantity = materialList[i]['quantity'];
		var materialname = materialList[i]['materialname'];
		var fileid="";
		var fileurl = materialList[i]['fileurl'];
		
		var trStr = '<tr>																													'+
					'	<td><span name="serialnumber">'+ index +'</span></td>																'+
					'	<td style="text-align: left;"><span name="materialname">'+ materialname + '</span>' + ismustsubmitStr +'</td>		'+
					'	<td>'+ quantity +'</td>																								'+
					'	<td id="filename_'+ index +'">																						'+
					'		'+ fileurl +'																									'+
					'	</td>																												'+
					'</tr>';
		
		$('#' + tableID).find('tbody').append(trStr);
	}
}

function save(){
	var users = [];
	$('#' + selectID).find("option:selected").each(function(){
		users.push(jQuery.parseJSON($(this).attr('data')));
	})

	var annexids = [];
	$("a[id^='annexid']").each(function(){
		annexids.push(jQuery.parseJSON($(this).attr('data')));
	})
	
	var businessid = applyid;
	var nodecode = nodeno;
	var opinion = $('#opinion').val();
	
	var formdata = {};
	formdata['businessid'] = businessid;
	formdata['nodecode'] = nodecode;
	formdata['opinion'] = opinion;
	formdata['nextnodecode'] = nextnodecode1;
	formdata['instanceid']= instanceid;
	formdata['taskid']= flowtaskid;
	formdata['taskuserid']= taskuserid;


	var correctionData = [];
	$('#materialList').find('tbody').find('tr').each(function(){
		var obj = $(this).find('[type="checkbox"]'); 
		var objCheck = obj.is(':checked');
		if(objCheck){
			var index = obj.attr('value');
			
			var correction = {};
			correction['attachmaterialid'] = $('#attachmaterialid_' + index).val();
			correction['quantity'] = $('#quantity_' + index).val();
			
			correctionData.push(correction);
		}
	})

	var params = {};
	params['auditopinion'] = formdata;
	params['users'] = users;
	params['annexids'] = annexids
	if(correctionData.length > 0)
		params['correction'] = correctionData;
	
	
	if(!check(formdata, users, correctionData))
		return true;

	
	$.ajax({ 
		method: 'post',
		url: basePath() + 'flow/jointlysignaccept.do',
		data: JSON.stringify(params),
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
				window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.success,{
					onOk:function(v){
			    		parent.refreshData();		//刷新数据
					}
				});	
	    	} 
	    	else{
	    		window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.error);
	    	}
      	}
	});
}


function check(formdata, users, correctionData){	
	var result = true;
	var strMsg = "";
	
	if(formdata['nextnodecode'] == '')	
		strMsg += '请选择下一步<br />';

	if(formdata['opinion'] == '')	
		strMsg += '请输入意见<br />';
	
//	if(users.length == 0)
//		strMsg += '请选择用户<br />';
	

	if(nodename.indexOf('补正') >= 0 && correctionData.length == 0){
		strMsg += '请选择需补正的材料<br />';
	}
		
	if(strMsg != ""){
    	window.wxc.xcConfirm(strMsg, window.wxc.xcConfirm.typeEnum.warning);
    	result = false;
	}
	
	return result;
}


function bindDetailList(data){

//	alert(JSON.stringify(data));
	
	var attachmaterialid = "";
	var index = 1;
    var materialname = "";
    var remark = "";
    var showmethod = "";
    var verifymethod = "";
    var typecode = "";
    var ismustsubmit = "";
    var quantity=1;
    if(data != null){
    	attachmaterialid = data.attachmaterialid;
    	index = data.serialnumber;
    	materialname = data.materialname;
    	remark = data.remark;
    	showmethod = data.showmethod;
    	verifymethod = data.verifymethod;
    	typecode = data.typecode;
    	ismustsubmit = data.ismustsubmit;
    	quantity = data.quantity;
    }

	var trStr = '<tr class="data">'+
			    '    <td>'+
			    '		<input onchange="checkOption($(this));" type="checkbox" value="'+ index +'">				'+
			    '    </td>'+
			    '    <td>'+
			    '		'+ index +'				'+
			    '    </td>'+
			    '    <td style="text-align: left;">'+
			    '    	'+ materialname +''+
				'		<input type="hidden" id="materialname_'+ index +'" value="'+ materialname +'">'+
		        '	</td>'+
			    '    <td>'+
			    '    	<input id="quantity_'+ index +'" type="number" class="form-control" value="'+quantity+'">'+
				'		<input type="hidden" id="attachmaterialid_'+ index +'" value="'+ attachmaterialid +'">'+
			    '    </td>'+
			    '</tr>';
	
	$('#materialList').find('tbody').append(trStr);
}

function checkOption(obj){
	var materialnames = "";
	
//	var objCheck1 = obj.is(':checked');
//	if(objCheck1){
		$('#materialList').find('tbody').find('tr').each(function(){
			var obj = $(this).find('[type="checkbox"]'); 
			var objCheck = obj.is(':checked');
			if(objCheck){
				var index = obj.attr('value');
				
				var materialname = $('#materialname_' + index).val();
				materialnames += index + "、" + materialname + "；"
			}
		})
//	}
	
	if(materialnames != ""){
		materialnames = materialnames.substring(0, materialnames.length);
	
		$('#opinion').val(materialnames);
	}
}


//获取节点信息，判断是否需要会签
function getNodeParamInfo(nodecode){
	$.ajax({ 
		url: basePath() + 'flow/getnodeparaminfo.do',
		data: {"itemno": itemno, "nodecode": nodecode},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		if(data.datas.isjointlysign == 1){	//会签节点，显示会签tab
	    			$('#jointlysigninfo').show();
	    		}
	    	}
      	}
	});
}

function bindingJointlySignInfo(){
	$.ajax({ 
		url: basePath() + 'business/getjointlysignopinion.do',
		data: {"instanceid":pinstanceid},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
			if(data.result == 1){
				var opinionData = data.datas;
				for(var i = 0; i < opinionData.length; i++){
					var nodename = opinionData[i].nodename;
					var username = opinionData[i].username;
					var audittime = formatDate(opinionData[i].audittime, 'yyyy-mm-dd hh:mi');
					var orgname = opinionData[i].orgname;
					var opinion = opinionData[i].opinion;
					var opinionid = opinionData[i].opinionid;	
					var orgcode=opinionData[i].orgcode;
					var trStr = ''+
					  '	<tr>'+
					  '		<td>'+
					  		username +
					  '		</td>'+
					  '		<td>'+
					  		orgname + '（'+ orgcode +'）' +
					  '		</td>'+
					  '		<td></td>'+
					  '		<td>'+
					  		opinion+			
					  '		</td>'+
					  '		<td>'+
					  '<span id="annex'+opinionid+'"></span>'+
					  '		</td>'+
					  '	</tr>';	
					$('#jointlysigntable').find('tbody').append(trStr);
					$.ajax({ 
						url: basePath() + 'business/getaduitannex.do',
						data: {"opinionid": opinionid},
						dataType: "json",
						async:false,
				        contentType: "application/json",
						success: function(data){
							if(data.result == 1){
								for(var j=0; j<data.datas.length; j++){
									var html='<a target="_blank" href="/gahCMP/business/getannexidbyid.do?annexid='+data.datas[j].annexid+'"><button type="button" class="btn btn-link">'+data.datas[j].filename+'</button></a>';
						             $("#annex"+opinionid).append(html);  
								}
							}
				      	}
					});
				}
			}
      	}
	});
}

function bindingJointlySignOpinion(){
	$.ajax({ 
		url: basePath() + 'flow/selectjointlysignnode.do',
		data: JSON.stringify({"instanceid":pinstanceid}),
		dataType: "json",
		type:"POST",
        contentType: "application/json",
		success: function(data){
			if(data.result == 1){
				for(i=0;i<data.datas.length;i++){
					$.ajax({ 
						url: basePath() + 'business/selectJointlySignOpinion.do',
						data: JSON.stringify({"instanceid": pinstanceid,"nodecode":data.datas[i].NODECODE}),
						dataType: "json",
						type:"POST",
						async:false,
				        contentType: "application/json",
						success: function(opiniondata){
							if(opiniondata.result==1){
								$('#jointlysignopinion').show();
								var html= '<div class="panel panel-primary" style="margin-top:10px">'+
								'<div class="panel-heading">'+
								'<h3 class="panel-title">'+
								data.datas[i].NODENAME+
								'会签信息'+
								'</div><div class="panel-body"><table class="table table-bordered" style="text-align: center;"><tr><th style="text-align: center;background-color: #eee;">用户名称</th><th style="text-align: center;background-color: #eee;">所属机构</th><th style="text-align: center;background-color: #eee;">处理建议</th><th style="text-align: center;background-color: #eee;">会签意见</th><th style="text-align: center;background-color: #eee;">附件</th></tr><tbody id="jointlysignnodecode'+data.datas[i].NODECODE+'"></tbody></table></div></div>';
								$("#jointlysignopiniontable").append(html);
								for(j=0;j<opiniondata.datas.length;j++){
									var trStr = ''+
									  '	<tr>'+
									  '		<td>'+
									  		opiniondata.datas[j].username +
									  '		</td>'+
									  '		<td>'+
									  		opiniondata.datas[j].orgname + '（'+ opiniondata.datas[j].orgcode +'）' +
									  '		</td>'+
									  '		<td>'+
									  		(opiniondata.datas[j].handleproposal?opiniondata.datas[j].handleproposal:"")+
									  '     </td>'+
									  '		<td>'+
									  		(opiniondata.datas[j].opinion?opiniondata.datas[j].opinion:"")+
									  '     </td>'+
									  '		<td>'+
									  '<span id="annex'+(opiniondata.datas[j].opinionid?opiniondata.datas[j].opinionid:"")+'"></span>'+
									  '		</td>'+
									  '	</tr>';	
									$("#jointlysignnodecode"+data.datas[i].NODECODE).append(trStr);
									if(opiniondata.datas[j].opinionid){
										$.ajax({ 
											url: basePath() + 'business/getaduitannex.do',
											data: {"opinionid": opiniondata.datas[j].opinionid},
											dataType: "json",
											async:false,
									        contentType: "application/json",
											success: function(annexdata){
												if(annexdata.result == 1){
													for(var k=0; k<annexdata.datas.length; k++){
														var html='<a target="_blank" href="/gahCMP/business/getannexidbyid.do?annexid='+annexdata.datas[k].annexid+'"><button type="button" class="btn btn-link">'+annexdata.datas[k].filename+'</button></a>';
											             $("#annex"+ opiniondata.datas[j].opinionid).append(html);  
													}
												}
									      	}
										});
									}
									
								}
							}
				      	}
					});
				}
			}
			
      	}
	});
}